package com.example.system.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 *
 * @ClassName: WebSocketComponent
 * @Description: Socket对外接口
 * @Author: Ian
 * @Date: 2017/5/9 10:57
 * @Version: 1.0
 */

@ServerEndpoint(value = "/websocket", encoders = { ServerEncoder.class },configurator=GetHttpSessionConfigurator.class)
@Component
public class WebSocketComponent {
    private static int onlineCount = 0;
    private static final Logger logger = LoggerFactory.getLogger(WebSocketComponent.class);

    /**
     * @MethodName: 连接建立成功调用的方法
     * @Description: open webSocket
     * @Author: Ian
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        if (WebSocketUtils.SessionSet.add(session)){
            addOnlineCount();           //在线数加1
            logger.info("有新连接加入！当前在线人数为{}", getOnlineCount());
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        WebSocketUtils.SessionSet.remove(session);
        subOnlineCount();           //在线数减1
        logger.info("有一连接关闭！当前在线人数为{}", getOnlineCount());
        closeSession(session);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(Session session, String message) {
        System.out.println("来自客户端消息:" + message);
    }

    /**
     * 发生错误时调用
     *
     * @OnError
     **/
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("服务端webSocket发生错误",error);
        closeSession(session);
    }

    private void closeSession (Session session) {
        try {
            session.close();
        } catch (IOException e) {
            logger.error("关闭webSocket session失败",e);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketComponent.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketComponent.onlineCount--;
    }

}
